#! /usr/bin/env python
# Push Change Test
import os
import sys
import time 
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtCore import Qt

import Sword
from pprint import pprint

class TextEditor(QtGui.QMainWindow):    

    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setWindowTitle('My Text Editor')
        #self.setWindowIcon(QtGui.QIcon('icons/web.png'))
        self.bookList = self.getAllBooks()
        pprint(self.bookList)
        self.__textEdit = QtGui.QTextEdit()
        self.setCentralWidget(self.__textEdit)

        #self.qb = GridLayout(self, self)
        #self.setCentralWidget(self.qb)
        self.dockGrid = DockGrid(self)
        self.qb2 = ButtonGrid(self.dockGrid,self,self.bookList)
        self.dockGrid.setWidget(self.qb2)
        self.addDockWidget(Qt.LeftDockWidgetArea,self.dockGrid)

        self.cwName = 'grid'

        exitAction = QtGui.QAction('Exit', self)
        self.connect(exitAction, QtCore.SIGNAL('triggered()'), self.close)

        newFileAction = QtGui.QAction('New', self)
        self.connect(newFileAction, QtCore.SIGNAL('triggered()'), self.newFile)

        openAction = QtGui.QAction('Open', self)
        self.connect(openAction, QtCore.SIGNAL('triggered()'), self.open)

        saveAction = QtGui.QAction('Save', self)
        self.connect(saveAction, QtCore.SIGNAL('triggered()'), self.save)

        saveAsAction = QtGui.QAction('Save As', self)
        self.connect(saveAsAction, QtCore.SIGNAL('triggered()'), self.saveAs)

        menubar = self.menuBar()
        file = menubar.addAction(newFileAction)
        file = menubar.addAction(openAction)
        file = menubar.addAction(saveAction)
        file = menubar.addAction(saveAsAction)
        file = menubar.addAction(exitAction)

        self.__fileName = ""

        #self.statusBar()
        #self.statusBar().showMessage('Ready')
        self.swap = QtGui.QAction('Swap', self)
        print self.swap.text()
        self.swap.setText('Book')
        print self.swap.text()
        #self.connect(self.swap, QtCore.SIGNAL('triggered()'), 
        #             self.dockGrid.toggleView)#, QtCore.SLOT('toggleViewAction'))#, QtCore.SLOT('toggleViewAction()'))#swapDisplay)
        self.bookButton = self.dockGrid.toggleViewAction()#QtGui.QAction('Swap', self)
        self.bookButton.setText('Book')
        self.toolbar = self.addToolBar('Swap')
        self.toolbar.setToolButtonStyle(Qt.ToolButtonTextOnly)
        print self.toolbar.minimumHeight(),self.toolbar.height(),self.toolbar.maximumHeight()
        self.toolbar.setMinimumHeight(60)
        self.toolbar.setIconSize(QtCore.QSize(120,80))
        self.toolbar.addAction(self.bookButton)#self.dockGrid.toggleViewAction())
        #size =  self.geometry()
        #print size

    def swapDisplay(self, event=None):
        if self.cwName == 'grid':
            self.removeDockWidget(self.dockGrid)
            #self.__textEdit = QtGui.QTextEdit()
            #self.setCentralWidget(self.__textEdit)
            self.cwName = 'text'
        else:
            self.addDockWidget(Qt.LeftDockWidgetArea,self.dockGrid)
            #self.qb = GridLayout(self)
            #self.setCentralWidget(self.qb)
            self.cwName = 'grid'

    def getAllBooks(self):
        """
         Return an array:
         [{'testament': 1, 'bookCount': 1, 'name': 'Genesis', 'abbr': 'Gen'},
         {'testament': 1, 'bookCount': 2, 'name': 'Exodus', 'abbr': 'Exod'},
        """
        if os.path.isfile('/home/user/bookList.pyd'):
            try: 
                bookList = eval(open('/home/user/bookList.pyd').read())
                return bookList
            except: pass
        vk=Sword.VerseKey()
        out=[]
        for i in range(1,3):
            vk.Testament(i)
            for j in range(1,vk.bookCount(i)+1):
                vk.Book(j)
                tmp={}
                tmp['name']=vk.bookName(i,j)
                tmp['abbr']=vk.getBookAbbrev()
                tmp['testament']=i
                tmp['bookCount']=j
                tmp['chapterCount']=vk.chapterCount(i,j)
                out.append(tmp)
        pprint(out,open('/home/user/bookList.pyd','w'))
        return out

    def newFile(self):
        self.__textEdit.clear()
        self.__fileName = ""

    def open(self):
        size =  self.geometry()
        print size

        self.__textEdit.clear()
        self.__fileName = QtGui.QFileDialog.getOpenFileName(self,
                       "Open", ".", "All Files (*)")

        if self.__userSelectedAFile():
            try:
                fsock = open(self.__fileName, "r")
                self.__textEdit.setPlainText(fsock.read())
                fsock.close()
            except Exception, e:
                QtGui.QMessageBox.critical(self, "Open error", e.message)

    def save(self):
        if not self.__userSelectedAFile():
            self.__openSaveAsDialog()

        if self.__userSelectedAFile():
            try:
                fsock = open(self.__fileName, "w")
                fsock.write(self.__textEdit.document().toPlainText())
                fsock.close()
            except Exception, e:
                QtGui.QMessageBox.critical(self, "Save error", e.message)

    def saveAs(self):
        self.__openSaveAsDialog()

        if self.__userSelectedAFile():
            self.save()

    def closeEvent2(self, event):
        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def __openSaveAsDialog(self):
        self.__fileName = QtGui.QFileDialog.getSaveFileName(self,
                       "Save As", ".", "Text Files (*.txt)")
        if self.__userSelectedAFile() and not self.__fileName.endsWith(".txt", QtCore.Qt.CaseInsensitive):
            self.__fileName = self.__fileName + ".txt"

    def __userSelectedAFile(self):
        return self.__fileName != ""

class ButtonGrid(QtGui.QWidget):
    def __init__(self, parent, master, buttonList=None):
        QtGui.QWidget.__init__(self, parent)

        self.setMaximumWidth(720)
        self.setWindowTitle('grid layout')
        grid = QtGui.QGridLayout()
        if buttonList == None:
            for row in range(5):
                for col in range(8):
                    button = QtGui.QPushButton('%s,%s' % (row,col))
                    self.connect(button, QtCore.SIGNAL('clicked()'), parent.toggleViewAction)#master.swapDisplay)
                    grid.addWidget(button,row,col)
        else:
            for ii in range(len(buttonList)):
                row = ii/9
                col = ii%9
                button = QtGui.QPushButton(buttonList[ii]['abbr'])#'%s,%s' % (row,col))
                self.connect(button, QtCore.SIGNAL('clicked()'), parent.toggleViewAction)#master.swapDisplay)
                grid.addWidget(button,row,col)
        self.setLayout(grid)

class DockGrid(QtGui.QDockWidget):
    def __init__(self, parent):
        QtGui.QDockWidget.__init__(self, parent)

        self.setFeatures(QtGui.QDockWidget.NoDockWidgetFeatures) # Is this the right thing type
        self.setAllowedAreas(Qt.AllDockWidgetAreas) # Or is this the right type?
        #self.setWidget = child
        #grid = self.QtGui.QGridLayout()
        #for row in range(5):
            #for col in range(8):
                #button = QtGui.QPushButton('%s,%s' % (row,col))
                #self.connect(button, QtCore.SIGNAL('clicked()'), parent.swapDisplay)
                #grid.addWidget(button,row,col)
        #self.setLayout(grid)
    def toggleView(self):
        print 'Toggling'
        self.toggleViewAction()
        print 'Toggled'

if __name__ == '__main__':    

    #Creating Qt application
    app = QtGui.QApplication(sys.argv)

    myTextEditor = TextEditor()
    myTextEditor.show()

    #Initing application
    sys.exit(app.exec_())
